package com.mbinno.android.comm.utils;

import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class SimHash {

    public static final int HASH_BITS = 64; // SimHash的位数
    private static final int NEAR_THRESHOLD = 3; // 汉明距离阈值

    public static long calculateSimHash(Map<String, Integer> wordMap) {
        // 计算加权特征向量
        int[] featureVector = new int[HASH_BITS];
        for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
            String word = entry.getKey();
            int weight = entry.getValue();
            long hash = getHexHashString(word);
            for (int i = 0; i < HASH_BITS; i++) {
                if (((hash >> i) & 1) == 1) {
                    featureVector[i] += weight;
                } else {
                    featureVector[i] -= weight;
                }
            }
        }

        // 生成SimHash值
        long simHash = 0;
        for (int i = 0; i < HASH_BITS; i++) {
            if (featureVector[i] > 0) {
                simHash |= 1L << i;
            }
        }

        return simHash;
    }
    public static long getHexHashString(String str) {
        HashFunction hashFunction = Hashing.murmur3_128();
        return hashFunction.hashString(str, StandardCharsets.UTF_8).asLong();
    }


    public static int hammingDistance(long simHash1, long simHash2) {
        long xor = simHash1 ^ simHash2;
        int distance = 0;
        while (xor != 0) {
            distance++;
            xor &= xor - 1;
        }
        return distance;
    }




}
